package com.tanhua.server.service;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.autoconfig.util.ValidateCodeUtils;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.domain.mysql.User;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.exception.ErrorResult;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class UserService {

    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @DubboReference
    private UserApi userApi;
    @DubboReference
    private UserLikeApi userLikeApi;
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private UserFreezeService userFreezeService;
    @Autowired
    private MqMessageService mqMessageService;
    @Autowired   //redis缓存
    private RedisTemplate<String, String> redisTemplate;
    @Autowired    //mq
    private AmqpTemplate amqpTemplate;

    //发送验证码
    public void sendMsg(String phone) {
        //根据手机号查询用户,构造redis的key判断是否被冻结
        User user = userApi.findByMobile(phone);
        //判断用户是否为空,为空则是新用户,不需要判断
        if (user != null) {
            userFreezeService.chekUserStatus("1", user.getId());
        }

        //获取验证码
        Integer integer = ValidateCodeUtils.generateValidateCode(6);
        String code = integer.toString();
        //发送验证码
        //smsTemplate.sendSms(phone,code);
        //存入缓存
        redisTemplate.opsForValue().set(phone, code, Duration.ofMinutes(5));
        log.info(code);

    }

    //登录
    public Map loginVerification(String phone, String code) {
        //1、从redis中获取下发的验证码
        String redisCode = redisTemplate.opsForValue().get(phone);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //验证码无效
            throw new BusinessException(ErrorResult.loginError());
        }
        //3、删除redis中的验证码
        redisTemplate.delete(phone);
        //4、通过手机号码查询用户
        User user = userApi.findByMobile(phone);
        boolean isNew = false;
        //日志要记录的状态状态
        String type = "0101";  //登录
        //5、如果用户不存在，创建用户保存到数据库中
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;
            type = "0102";  //注册
        }
        if (user.getHxUser() == null) {
            //注册环信用户
            String hxUser = "hx" + user.getId();
            System.out.println("111111111111111111111111" + hxUser);
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if (create) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }

        //记录日志
        mqMessageService.sendLogMessage(user.getId(), type, "user", null);

        //6、通过JWT生成token(存入id和手机号码)
        Map tokenMap = new HashMap();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", phone);
        String token = JwtUtils.getToken(tokenMap);
        //7、构造返回值
        Map retMap = new HashMap();
        retMap.put("token", token);
        retMap.put("isNew", isNew);

        return retMap;
    }

    //互相喜欢，喜欢，粉丝 - 统计
    public Map<String, Integer> findCounts() {
        //查询 喜欢，粉丝
        Map map = userLikeApi.findCountAll(UserHolder.getUserId());
        //喜欢
        List<Long> loveCount = (List<Long>) map.get("loveCount");
        //粉丝
        List<Long> fanCount = (List<Long>) map.get("fanCount");

        //互相喜欢
        List<Long> eachLoveCount = new ArrayList<>();
        eachLoveCount.addAll(loveCount);
        //保留 arraylist 中在指定集合中也存在的那些元素,也就是删除指定集合中不存在的那些元素
        eachLoveCount.retainAll(fanCount);//去两个集合的并集

        Map<String, Integer> listMap = new HashMap<>();
        listMap.put("eachLoveCount", eachLoveCount.size());
        listMap.put("loveCount", loveCount.size());
        listMap.put("fanCount", fanCount.size());
        return listMap;
    }
}



